<?php

/**
 * 基础控制器
 *
 * @author jackson_xu@outlook.com
 */

namespace Admin\Controller;

use Think\Controller;
use Think\Page;
use Org\Util\Rbac;

class BaseController extends Controller {

    public $limit = 10;

    /**
     * 基础验证登陆
     */
    public function _initialize() {
       //echo "a";die;
        if (!session(C('USER_AUTH_KEY'))) {
            $this->redirect('Admin/Login/index');
        }
        $not_auth = in_array(CONTROLLER_NAME, explode(',', C('NOT_AUTH_MODULE'))) || in_array(ACTION_NAME, explode(',', C('NOT_AUTH_FUNCTION')));

        //判断是否开启登陆验证
        if (C('USER_AUTH_ON') && !$not_auth) {
            Rbac::AccessDecision() || $this->error('没有权限进行操作');
        }

        //排除控制器
        $array = array("Index", "Database", "Rbac",'SiteContentPdf','visitor');
        if (!in_array(CONTROLLER_NAME, $array)) {
           $this->model = D(CONTROLLER_NAME);
        }
        $map['url'] = array('like', CONTROLLER_NAME . "/" . ACTION_NAME . '%');
        $this_menu = D('backmenu')->where($map)->find();
        if ($this_menu['pid'] == 0) {
            $menu_id = $this_menu['id'];
        } else {
            $menu_id = $this_menu['pid'];
        }
        //根据用户角色选择显示的菜单
        if (empty($_SESSION[C('ADMIN_AUTH_KEY')])) {
            $roleMap['user_id'] = session(C('USER_AUTH_KEY'));
            $roles = M('roles_users')->where($roleMap)->getField('role_id', true);
            $menu_ids = array();
            foreach ($roles as $role) {
                $menus = M('roles')->getFieldById($role, 'menu_ids');
                $menu_ids = array_unique(array_merge($menu_ids, explode('-', $menus)));
            }
        }

        $this->top_menus = $this->getMenus($menu_ids);

        if (isset($menu_id)) {
            $this->extra_menu = $this->getExtraMenu($menu_id, $menu_ids);
        }
    }

    /**
     * 获取控制器菜单数组,二级菜单元素位于一级菜单的'_child'元素中
     * @author jackson.xu@wemax.org
     */
    final public function getMenus($menu_ids) {
        // $menus  =   session('ADMIN_MENU_LIST'.$controller);
        if (empty($menus)) {
            // 获取主菜单
            $where['pid'] = 0;
            $where['hide'] = 0;
            $menu_ids && $where['id'] = array('in', $menu_ids);
            if (!C('DEVELOP_MODE')) { // 是否开发者模式
                $where['is_dev'] = 0;
            }
            //当前用户角色的menu_ids取出，imploe 一维数组，  当前menu一级栏目的menu_ids  array_intersect
            $menus = M('backmenu')->where($where)->order('sort ASC')->select();
            return $menus;
        }
    }

    final public function getExtraMenu($praent_menu_id) {
        if ($praent_menu_id) {
            $map['pid'] = $praent_menu_id;
            $map['hide'] = 0;
            $menu_ids && $where['id'] = array('in', $menu_ids);
            $menu = M('backmenu')->where($map)->order('sort ASC')->select();
        }
        return $menu;
    }

    protected function lists($count, $limit) {
        if ($limit) {
            $limit = 10;
        }
        $Page = new \Think\Page($count, $limit);
        $Page->setConfig('header', '个文章');
        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('first', '第一页');
        $Page->setConfig('last', '最后页');
        return $Page;
    }

    //查询条件
    public function searchConditionById() {
        $id = I('id', '', 'intval');
        $map['id'] = $id;
        return $map;
    }

    //公共查询条件
    public function searchConditionByName() {
        $map['name'] = array('like', '%' . trim(I('name')) . '%');
        return $map;
    }

    public function searchConditionByActive($active = 0) {
        $map['is_active'] = $active;
        return $map;
    }

    //图片上传
    public function up_pic() {
        $oldimg = $_POST["oldimg"]; //之前长传的图片
        unlink("." . $oldimg); //删除之前的图片
        $file = $_POST['imgfile'];
        if ($file) { //图片保存文件夹
            $file = $file . "/";
        }
        $config = array(
            'maxSize' => 3145728,
            'rootPath' => './Public/Uploads/' . $file,
            'exts' => array('jpg', 'gif', 'png', 'jpeg'),
            'subName' => '',
        );
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传文件 

        $info = $upload->uploadOne($_FILES['file']);
        $url = "/Public/Uploads/" . $file . $info['savepath'] . $info['savename'];
        if (!$info) {
            $this->ajaxReturn("false", "EVAL");
        } else {
            $this->ajaxReturn($url, "EVAL");
        }
    }

    //删除图片
    public function delimg() {
        $imgurl = $_POST["imgurl"]; //之前长传的图片
        unlink("." . $imgurl); //删除之前的图片
        $this->ajaxReturn(true);
    }

    //图片裁剪保存
    public function imgcrop() {
        if ($_POST) {
            //获取原图路径
            $src = $_POST['src'];
            //取得原图像的信息
            $source_path = substr($src, 1); //截取“/Public”后面的字母
            //取得原图像的信息
            $source_info = getimagesize($source_path);
            $source_w = $source_info[0];
            $source_h = $source_info[1];
            $source_mime = $source_info['mime'];

            //取得页面截取参数
            $postx = $_POST['x'];
            $posty = $_POST['y'];
            $postw = $_POST['w'];
            $posth = $_POST['h'];

            //确定实际图像的x、y、w、h
            $true_x = $postx;
            $true_y = $posty;
            $true_w = $postw;
            $true_h = $posth;
            //目标存储规格
            $targ_w = $_POST['targw'];
            $targ_h = $_POST['targh'];
            $jpeg_quality = 90;
            //根据图片类型创建
            switch ($source_mime) {
                case 'image/gif':
                    $source_image = imagecreatefromgif($source_path);
                    break;

                case 'image/jpeg':
                    $source_image = imagecreatefromjpeg($source_path);
                    break;

                case 'image/png':
                    $source_image = imagecreatefrompng($source_path);
                    break;

                default:
                    return false;
                    break;
            }
            $source_image = imagecreatefromjpeg($source_path);
            $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
            imagecopyresampled($dst_r, $source_image, 0, 0, $true_x, $true_y, $targ_w, $targ_h, $true_w, $true_h);

            //根据图片类型存储图片
            switch ($source_mime) {
                case 'image/gif':
                    imagegif($dst_r, $source_path, $jpeg_quality);
                    break;

                case 'image/jpeg':
                    imagejpeg($dst_r, $source_path, $jpeg_quality);
                    break;

                case 'image/png':
                    imagepng($dst_r, $source_path, $jpeg_quality);
                    break;

                default:
                    return false;
                    break;
            }
            imagedestroy($dst_r);
            $this->ajaxReturn($src);
        }
    }

    /**
     * 列表页
     */
    public function index() { 
        $model = $this->model;

        $contents = $model->order('sort')->select();

        $this->contents = $contents;
        $this->display();
    }

    /**
     * 公共编辑配置
     */
    public function edit($id = 0) {
        $id = I('id', 0);
        $model = $this->model;
        if (IS_POST) {
            $data = I('post.');
            if ($data) {
                $result = $model->save($data);
                if ($result != false) {
                    $this->success('更新成功', U('index'));
                } else {
                    $this->error('更新失败');
                }
            } else {
                $this->error('数据不正确');
            }
        } else {
            $info = array();
            /* 获取数据 */
            $info = $model->field(true)->find($id);

            if (false === $info) {
                $this->error('获取数据错误');
            }
            $this->assign('info', $info);
            $this->title = '编辑';
            $this->display();
        }
    }

    //公共删除
    public function delete() {

        //获得参数
        $id = array_unique((array) I('id', 0));
        $model = $this->model;
        $map = array('id' => array('in', $id));
        $result = $model->where($map)->delete();
        if ($result) {
            $this->success("删除成功");
        } else {
            $this->error("删除失败");
        }
    }
    
    
     public function uploads(){
        $file =$_FILES;
        $upload= new \Think\Upload();
        $upload->exts=array("jpg","jpeg","png","gif");
        $upload->savePath="./Public/Admin/images/upload/";
    
        $tag=$upload->uploadOne($file['thumb']);
        if(!tag){
            $this->error($upload->getError());
        }
         return $tag;
        
    }
    
    public function uploades(){
         $file =$_FILES;
        print_r($_FILES);
        $upload= new \Think\Upload();
        $upload->exts=array("jpg","jpeg","png","gif");
        $upload->savePath="./Public/Admin/images/upload/";
    
        $tag=$upload->upload($_FILES['images']);
        var_dump($tag);
        if(!tag){
            $this->error($upload->getError());
        }
         return $tag;
        
    }

}

?>
